<template>
  <div class="min-h-screen bg-gray-50 flex flex-col md:flex-row">
    <!-- 右侧主体内容 -->
    <div class="flex-1 h-screen overflow-y-auto">
      <!-- 顶部标题区域 -->
      <div class="p-4 md:p-8 pb-4 bg-white shadow-sm">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
          <div>
            <h1 class="text-xl md:text-2xl font-bold text-gray-800 mb-1">{{ paperInfo.title }}</h1>
            <p class="text-sm text-gray-500">完成时间：{{ formatDate(paperInfo.submitTime) }} · 用时：{{ paperInfo.usedTime }}分钟
            </p>
          </div>
          <!-- 修改顶部信息区域的统计数据 -->
          <div class="mt-4 md:mt-0 flex items-center">
            <div class="text-center mr-6">
              <div class="text-2xl font-bold text-blue-600">{{ questions.length }}</div>
              <div class="text-xs text-gray-500">总题数</div>
            </div>
            <div class="text-center mr-6">
              <div class="text-2xl font-bold text-green-600">{{questions.filter(q => q.isCorrect).length}}</div>
              <div class="text-xs text-gray-500">答对题数</div>
            </div>
            <div class="text-center mr-6">
              <div class="text-2xl font-bold" :class="getScoreColor(paperInfo.correctRate)">
                {{ (paperInfo.correctRate * 100).toFixed(1) }}%
              </div>
              <div class="text-xs text-gray-500">正确率</div>
            </div>
            <el-button type="primary" @click="exportReport">导出报告</el-button>
          </div>
        </div>
      </div>

      <!-- 分析内容区域 -->
      <div class="p-4 md:p-8">
        <!-- 总体分析卡片 -->
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
            <el-icon class="mr-2">
              <DataAnalysis />
            </el-icon>总体分析
          </h2>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 左侧：成绩雷达图 -->
            <div class="bg-gray-50 rounded-lg p-4">
              <h3 class="text-sm font-medium text-gray-700 mb-3">知识点掌握情况</h3>
              <div class="w-full h-[300px] flex items-center justify-center">
                <RadarChart :chartData="radarChartData" />
              </div>
            </div>

            <!-- 右侧：AI分析 -->
            <div class="bg-blue-50 rounded-lg p-4 border border-blue-100">
              <h3 class="text-sm font-medium text-blue-700 mb-3 flex items-center">
                <el-icon class="mr-1">
                  <ChatLineRound />
                </el-icon>AI学习建议
              </h3>
              <div v-if="loading" class="flex justify-center items-center h-48">
                <el-skeleton :rows="6" animated />
              </div>
              <div v-else class="text-sm text-gray-700 leading-relaxed">
                <p v-for="(item, index) in aiAnalysis" :key="index" class="mb-2">{{ item }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 知识点分析卡片 -->
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
            <el-icon class="mr-2">
              <Reading />
            </el-icon>知识点掌握分析
          </h2>

          <el-table :data="knowledgePoints" stripe style="width: 100%">
            <el-table-column prop="name" label="知识点" min-width="180" />
            <el-table-column prop="questionCount" label="题目数" width="100" align="center" />
            <el-table-column prop="correctCount" label="正确数" width="100" align="center" />
            <el-table-column label="正确率" width="180" align="center">
              <template #default="scope">
                <div class="flex items-center">
                  <el-progress :percentage="scope.row.correctRate * 100"
                    :color="getProgressColor(scope.row.correctRate)" :stroke-width="10"
                    :format="(percentage) => `${percentage.toFixed(0)}%`" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="掌握程度" width="120" align="center">
              <template #default="scope">
                <el-tag :type="getMasteryLevel(scope.row.correctRate).type" size="small">
                  {{ getMasteryLevel(scope.row.correctRate).label }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 题目分析卡片 -->
        <div class="bg-white rounded-xl shadow-sm p-6">
          <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
            <el-icon class="mr-2">
              <List />
            </el-icon>答题情况
          </h2>

          <!-- 答题卡部分 -->
          <div class="flex flex-wrap gap-2">
            <div v-for="(question, index) in questions" :key="question.id" class="relative cursor-pointer group"
              @click="handleQuestionClick(question)">
              <div class="w-10 h-10 rounded flex items-center justify-center border transition-all text-sm" :class="[
                question.isCorrect
                  ? 'border-green-500 bg-green-50 text-green-600'
                  : 'border-red-500 bg-red-50 text-red-600',
                selectedQuestion?.id === question.id ? 'ring-2 ring-blue-500' : ''
              ]">
                {{ index + 1 }}
              </div>
              <!-- 悬浮提示 -->
              <div
                class="absolute hidden group-hover:block bottom-full left-1/2 transform -translate-x-1/2 mb-1 w-max z-10">
                <div class="bg-gray-800 text-white text-xs rounded py-1 px-2 text-center whitespace-nowrap">
                  {{ getQuestionTypeName(question.type) }}
                  <div
                    class="absolute bottom-0 left-1/2 transform -translate-x-1/2 translate-y-1/2 rotate-45 w-2 h-2 bg-gray-800">
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 选中题目的详细信息 -->
          <div v-if="selectedQuestion" class="border-t border-gray-100 mt-6 pt-4">
            <!-- 知识点标签 -->
            <div class="flex flex-wrap gap-2 mb-3">
              <el-tag v-for="point in selectedQuestion.knowledgePoints" :key="point.id" size="small" effect="plain">
                {{ point.name }}
              </el-tag>
            </div>
            <!-- 题目内容 -->
            <div class="mb-4">
              <div class="text-base font-medium text-gray-800 mb-3" v-html="selectedQuestion.content"></div>

              <!-- 选择题选项 -->
              <div v-if="['single', 'multiple', 'truefalse'].includes(selectedQuestion.type)" class="space-y-2">
                <div v-for="(option, key) in selectedQuestion.options" :key="key" :class="[
                  'p-2 border rounded flex items-start',
                  getOptionClass(selectedQuestion, key)
                ]">
                  <div class="flex-shrink-0 mr-2">
                    <div :class="[
                      'w-6 h-6 flex items-center justify-center rounded-full border text-sm',
                      getOptionIconClass(selectedQuestion, key)
                    ]">
                      {{ selectedQuestion.type === 'truefalse' ? (key === true ? '√' : '×') : key }}
                    </div>
                  </div>
                  <div class="flex-1" v-html="option"></div>
                </div>
              </div>

              <!-- 填空题答案 -->
              <div v-else-if="selectedQuestion.type === 'fillblank'" class="space-y-2">
                <div v-for="(blank, index) in selectedQuestion.blanks" :key="index" class="flex items-center">
                  <span class="mr-2 text-gray-600">第{{ index + 1 }}空：</span>
                  <div class="flex items-center">
                    <div class="px-3 py-1 border rounded"
                      :class="blank.isCorrect ? 'border-green-300 bg-green-50' : 'border-red-300 bg-red-50'">
                      {{ blank.userAnswer || '(未作答)' }}
                    </div>
                    <el-icon v-if="blank.isCorrect" class="ml-2 text-green-500">
                      <Check />
                    </el-icon>
                    <div v-else class="ml-2 flex items-center text-red-500">
                      <el-icon>
                        <Close />
                      </el-icon>
                      <span class="ml-1">正确答案: {{ blank.correctAnswer }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 应答题答案 -->
              <div v-else-if="selectedQuestion.type === 'essay'" class="space-y-3">
                <div class="p-3 border rounded bg-gray-50">
                  <div class="text-sm text-gray-500 mb-1">你的答案：</div>
                  <div class="text-gray-800" v-html="selectedQuestion.userAnswer || '(未作答)'"></div>
                </div>
                <div class="p-3 border rounded bg-blue-50 border-blue-100">
                  <div class="text-sm text-blue-500 mb-1">参考答案：</div>
                  <div class="text-gray-800" v-html="selectedQuestion.correctAnswer"></div>
                </div>
              </div>
            </div>

            <!-- 解析 -->
            <div class="p-3 bg-yellow-50 border border-yellow-100 rounded-lg">
              <div class="text-sm font-medium text-yellow-800 mb-1">解析：</div>
              <div class="text-sm text-gray-700" v-html="selectedQuestion.analysis"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { ElMessage } from 'element-plus'
import {
  DataAnalysis, Reading, List, ChatLineRound,
  Check, Close, Download
} from '@element-plus/icons-vue'
import Nav from '@/components/nav/index.vue'
import RadarChart from '@/components/charts/RadarChart.vue'
import { getPaperResult } from '@/api/common'
import html2pdf from 'html2pdf.js'

export default {
  components: {
    Nav, RadarChart, DataAnalysis, Reading,
    List, ChatLineRound, Check, Close, Download
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(true)

    // 试卷信息
    const paperInfo = ref({
      id: '',
      title: '期末考试分析报告',
      submitTime: new Date(),
      usedTime: 45,
      totalScore: 100,
      correctRate: 0.85
    })

    // 题目列表
    const questions = ref([])

    // 知识点分析
    const knowledgePoints = ref([])

    // AI分析
    const aiAnalysis = ref([])

    // 雷达图数据
    const radarChartData = computed(() => {
      return {
        labels: knowledgePoints.value.map(point => point.name),
        datasets: [
          {
            label: '掌握程度',
            data: knowledgePoints.value.map(point => point.correctRate * 100),
            backgroundColor: 'rgba(54, 162, 235, 0.2)',
            borderColor: 'rgba(54, 162, 235, 1)',
            pointBackgroundColor: 'rgba(54, 162, 235, 1)',
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: 'rgba(54, 162, 235, 1)'
          }
        ]
      }
    })

    // 加载分析数据
    // const loadAnalysisData = async () => {
    //   try {
    //     loading.value = true
    //     const paperId = route.query.paper_id

    //     if (!paperId) {
    //       ElMessage.error('试卷ID不存在')
    //       router.push('/dashboard')
    //       return
    //     }

    //     // 调用API获取分析数据
    //     const result = await getPaperResult({ id: paperId })

    //     // 更新试卷信息
    //     paperInfo.value = {
    //       id: result.paper.id,
    //       title: result.paper.title,
    //       submitTime: new Date(result.submitTime),
    //       usedTime: result.usedTime,
    //       score: result.score,
    //       totalScore: result.totalScore,
    //       correctRate: result.correctRate
    //     }

    //     // 更新题目列表
    //     questions.value = result.questions.map(q => ({
    //       id: q.id,
    //       type: q.type,
    //       content: q.content,
    //       options: q.options,
    //       userAnswer: q.userAnswer,
    //       correctAnswer: q.correctAnswer,
    //       isCorrect: q.isCorrect,
    //       analysis: q.analysis,
    //       knowledgePoints: q.knowledgePoints,
    //       blanks: q.blanks
    //     }))

    //     // 更新知识点分析
    //     knowledgePoints.value = result.knowledgePoints.map(kp => ({
    //       id: kp.id,
    //       name: kp.name,
    //       questionCount: kp.questionCount,
    //       correctCount: kp.correctCount,
    //       correctRate: kp.correctRate
    //     }))

    //     // 更新AI分析
    //     aiAnalysis.value = result.aiAnalysis || [
    //       "根据你的答题情况，你在「数学运算」方面表现优秀，建议可以尝试更高难度的题目。",
    //       "「几何证明」是你的薄弱环节，正确率仅为60%，建议重点复习相关知识点。",
    //       "你在「函数与导数」的应用题上有一定困难，建议多做此类型的练习题。",
    //       "整体来看，你的基础知识掌握较好，但在综合应用方面还需加强。",
    //       "建议针对错题进行专项训练，特别是那些涉及多个知识点的综合题目。"
    //     ]

    //   } catch (error) {
    //     console.error('加载分析数据出错：', error)
    //     ElMessage.error('加载分析数据失败，请刷新页面重试')
    //   } finally {
    //     loading.value = false
    //   }
    // }

    // 获取题型名称
    const getQuestionTypeName = (type) => {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        truefalse: '判断题',
        fillblank: '填空题',
        essay: '应答题'
      }
      return typeMap[type] || '未知题型'
    }

    // 获取选项样式类
    const getOptionClass = (question, key) => {
      if (question.type === 'truefalse') {
        if (question.correctAnswer === key && question.userAnswer === key) {
          return 'border-green-500 bg-green-50'
        } else if (question.correctAnswer === key) {
          return 'border-green-500 bg-green-50'
        } else if (question.userAnswer === key) {
          return 'border-red-500 bg-red-50'
        } else {
          return 'border-gray-200'
        }
      } else {
        const isUserSelected = Array.isArray(question.userAnswer)
          ? question.userAnswer.includes(key)
          : question.userAnswer === key

        const isCorrectAnswer = Array.isArray(question.correctAnswer)
          ? question.correctAnswer.includes(key)
          : question.correctAnswer === key

        if (isUserSelected && isCorrectAnswer) {
          return 'border-green-500 bg-green-50'
        } else if (isCorrectAnswer) {
          return 'border-green-500 bg-green-50'
        } else if (isUserSelected) {
          return 'border-red-500 bg-red-50'
        } else {
          return 'border-gray-200'
        }
      }
    }

    // 获取选项图标样式类
    const getOptionIconClass = (question, key) => {
      if (question.type === 'truefalse') {
        if (question.correctAnswer === key && question.userAnswer === key) {
          return 'bg-green-500 text-white border-green-500'
        } else if (question.correctAnswer === key) {
          return 'bg-green-500 text-white border-green-500'
        } else if (question.userAnswer === key) {
          return 'bg-red-500 text-white border-red-500'
        } else {
          return 'border-gray-300 text-gray-500'
        }
      } else {
        const isUserSelected = Array.isArray(question.userAnswer)
          ? question.userAnswer.includes(key)
          : question.userAnswer === key

        const isCorrectAnswer = Array.isArray(question.correctAnswer)
          ? question.correctAnswer.includes(key)
          : question.correctAnswer === key

        if (isUserSelected && isCorrectAnswer) {
          return 'bg-green-500 text-white border-green-500'
        } else if (isCorrectAnswer) {
          return 'bg-green-500 text-white border-green-500'
        } else if (isUserSelected) {
          return 'bg-red-500 text-white border-red-500'
        } else {
          return 'border-gray-300 text-gray-500'
        }
      }
    }

    // 获取进度条颜色
    const getProgressColor = (rate) => {
      if (rate >= 0.8) return '#67C23A'
      if (rate >= 0.6) return '#E6A23C'
      return '#F56C6C'
    }

    // 获取分数颜色
    const getScoreColor = (rate) => {
      if (rate >= 0.8) return 'text-green-600'
      if (rate >= 0.6) return 'text-yellow-600'
      return 'text-red-600'
    }

    // 获取掌握程度
    const getMasteryLevel = (rate) => {
      if (rate >= 0.8) return { label: '优秀', type: 'success' }
      if (rate >= 0.6) return { label: '良好', type: 'warning' }
      if (rate >= 0.4) return { label: '一般', type: 'info' }
      return { label: '需加强', type: 'danger' }
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    const exportReport = async () => {
  try {
    ElMessage.info('正在生成PDF报告，请稍候...')
    
    // 创建一个专门用于打印的容器
    const printContainer = document.createElement('div')
    printContainer.style.cssText = `
      width: 210mm;
      background: white;
      padding: 10px;
      font-family: Arial, sans-serif;
    `
    
    // 构建报告内容 - 使用简单的HTML结构
    printContainer.innerHTML = `
      <h1 style="font-size: 24px; font-weight: bold; margin-bottom: 16px;">${paperInfo.value.title}</h1>
      <!-- 基础信息横排展示 -->
      <div style="display: flex; flex-wrap: wrap; margin-bottom: 15px; color: #666; font-size: 13px;">
        <div style="margin-right: 20px;">完成时间：${formatDate(paperInfo.value.submitTime)}</div>
        <div style="margin-right: 20px;">用时：${paperInfo.value.usedTime}分钟</div>
        <div style="margin-right: 20px;">总题数：${questions.value.length}</div>
        <div style="margin-right: 20px;">答对题数：${questions.value.filter(q => q.isCorrect).length}</div>
        <div>正确率：${(paperInfo.value.correctRate * 100).toFixed(1)}%</div>
      </div>
      
      <h2 style="font-size: 18px; margin: 20px 0 10px 0;">知识点掌握情况</h2>
      <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
        <thead>
          <tr style="background-color: #f3f4f6;">
            <th style="padding: 8px; border: 1px solid #e5e7eb; text-align: left;vertical-align: middle;">知识点</th>
            <th style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">题目数</th>
            <th style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">正确数</th>
            <th style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">正确率</th>
            <th style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">掌握程度</th>
          </tr>
        </thead>
        <tbody>
          ${knowledgePoints.value.map(point => `
            <tr>
              <td style="padding: 8px; border: 1px solid #e5e7eb;vertical-align: middle;">${point.name}</td>
              <td style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">${point.questionCount}</td>
              <td style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">${point.correctCount}</td>
              <td style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">${(point.correctRate * 100).toFixed(1)}%</td>
              <td style="padding: 8px; border: 1px solid #e5e7eb; text-align: center;vertical-align: middle;">${getMasteryLevel(point.correctRate).label}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
      
      <h2 style="font-size: 18px; margin: 20px 0 10px 0;">答题情况</h2>
      <div style="display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 20px;">
        ${questions.value.map((question, index) => `
          <div style="
            width: 36px; 
            height: 36px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            border-radius: 4px;
            font-size: 14px;
            ${question.isCorrect 
              ? 'background-color: #ecfdf5; border: 1px solid #10b981; color: #10b981;' 
              : 'background-color: #fef2f2; border: 1px solid #ef4444; color: #ef4444;'
            }
          ">
            ${index + 1}
          </div>
        `).join('')}
      </div>
      
      <h2 style="font-size: 18px; margin: 20px 0 10px 0;">AI学习建议</h2>
      <div style="padding: 15px; background-color: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; margin-bottom: 20px;">
        ${aiAnalysis.value.map(item => `<p style="margin-bottom: 8px;">${item}</p>`).join('')}
      </div>
    `
    
    // 获取雷达图的canvas并转换为图片
    const radarCanvas = document.querySelector('.w-full.h-\\[300px\\] canvas')
    if (radarCanvas) {
      try {
        const radarImage = radarCanvas.toDataURL('image/png')
        const radarDiv = document.createElement('div')
        radarDiv.innerHTML = `
          <h2 style="font-size: 18px; margin: 20px 0 10px 0;">知识点分布图</h2>
          <div style="text-align: center; margin-bottom: 20px;">
            <img src="${radarImage}" style="max-width: 100%; height: auto;" />
          </div>
        `
        // 插入到内容前面
        printContainer.insertBefore(radarDiv, printContainer.querySelector('h2'))
      } catch (e) {
        console.error('雷达图转换失败:', e)
      }
    }
    
    // 添加到文档但隐藏
    printContainer.style.position = 'fixed'
    printContainer.style.left = '-9999px'
    document.body.appendChild(printContainer)
    
    // 等待内容渲染
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 使用jsPDF直接生成PDF
    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: 'a4'
    })
    
    // 使用html2canvas将内容转为图片
    const canvas = await html2canvas(printContainer, {
      scale: 2,
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff'
    })
    
    const imgData = canvas.toDataURL('image/jpeg', 1.0)
    const imgWidth = 210 - 20 // A4宽度减去边距
    const pageHeight = 297 - 20 // A4高度减去边距
    const imgHeight = (canvas.height * imgWidth) / canvas.width
    
    // 添加图片到PDF
    pdf.addImage(imgData, 'JPEG', 10, 10, imgWidth, imgHeight)
    
    // 如果内容超过一页，添加新页面
    let heightLeft = imgHeight - pageHeight
    let position = -pageHeight // 第二页开始位置
    
    while (heightLeft > 0) {
      pdf.addPage()
      pdf.addImage(imgData, 'JPEG', 10, position + 10, imgWidth, imgHeight)
      heightLeft -= pageHeight
      position -= pageHeight
    }
    
    // 保存PDF
    pdf.save(`${paperInfo.value.title}_分析报告.pdf`)
    
    // 清理临时元素
    document.body.removeChild(printContainer)
    
    ElMessage.success('PDF报告导出成功')
  } catch (error) {
    console.error('导出报告失败：', error)
    ElMessage.error('导出报告失败，请重试')
  }
}

    // 在 setup 函数中添加测试数据
    const mockData = {
      paper: {
        id: 'test-paper-001',
        title: '期中数学测试',
        submitTime: new Date(),
        usedTime: 45,
        score: 85,
        totalScore: 100,
        correctRate: 0.85
      },
      questions: Array.from({ length: 20 }, (_, i) => {
        const types = ['single', 'multiple', 'truefalse', 'fillblank', 'essay']
        const type = types[Math.floor(Math.random() * types.length)]
        const isCorrect = Math.random() > 0.3

        // 基础题目数据
        const baseQuestion = {
          id: `q-${i + 1}`,
          type,
          isCorrect,
          content: `<p>第${i + 1}题：这是一道${getQuestionTypeName(type)}，用于测试学生对相关知识点的掌握程度。题目包含了计算、推理和应用等多个层面。</p>`,
          analysis: '本题考察了基础概念的理解和实际应用能力。解题关键在于正确理解题意，运用相关公式进行分析和计算。',
          knowledgePoints: [
            { id: `kp-${Math.floor(i / 4) + 1}`, name: ['数与式', '方程与不等式', '函数', '几何', '统计与概率'][Math.floor(i / 4)] }
          ]
        }

        // 根据题型添加特定属性
        switch (type) {
          case 'single':
            return {
              ...baseQuestion,
              options: {
                A: '这是选项A的内容',
                B: '这是选项B的内容',
                C: '这是选项C的内容',
                D: '这是选项D的内容'
              },
              userAnswer: isCorrect ? 'A' : 'B',
              correctAnswer: 'A'
            }
          case 'multiple':
            return {
              ...baseQuestion,
              options: {
                A: '这是选项A的内容',
                B: '这是选项B的内容',
                C: '这是选项C的内容',
                D: '这是选项D的内容'
              },
              userAnswer: isCorrect ? ['A', 'C'] : ['B', 'D'],
              correctAnswer: ['A', 'C']
            }
          case 'truefalse':
            return {
              ...baseQuestion,
              options: {
                true: '正确',
                false: '错误'
              },
              userAnswer: isCorrect ? true : false,
              correctAnswer: true
            }
          case 'fillblank':
            return {
              ...baseQuestion,
              blanks: [
                {
                  id: 1,
                  userAnswer: isCorrect ? '正确答案' : '错误答案',
                  correctAnswer: '正确答案',
                  isCorrect: isCorrect
                },
                {
                  id: 2,
                  userAnswer: isCorrect ? '正确答案2' : '错误答案2',
                  correctAnswer: '正确答案2',
                  isCorrect: isCorrect
                }
              ]
            }
          case 'essay':
            return {
              ...baseQuestion,
              userAnswer: isCorrect
                ? '这是一个接近正确答案的作答内容，展示了较好的理解...'
                : '这是一个部分正确的作答内容，但存在一些问题...',
              correctAnswer: '这是标准答案内容，包含了关键点和解题步骤...'
            }
        }
      }),
      knowledgePoints: [
        {
          id: 'kp-1',
          name: '数与式',
          questionCount: 5,
          correctCount: 4,
          correctRate: 0.8
        },
        {
          id: 'kp-2',
          name: '方程与不等式',
          questionCount: 4,
          correctCount: 3,
          correctRate: 0.75
        },
        {
          id: 'kp-3',
          name: '函数',
          questionCount: 6,
          correctCount: 5,
          correctRate: 0.83
        },
        {
          id: 'kp-4',
          name: '几何',
          questionCount: 3,
          correctCount: 2,
          correctRate: 0.67
        },
        {
          id: 'kp-5',
          name: '统计与概率',
          questionCount: 2,
          correctCount: 2,
          correctRate: 1.0
        }
      ],
      aiAnalysis: [
        "根据你的答题情况，你在「数与式」和「函数」方面表现优秀，继续保持！",
        "「几何」部分的正确率相对较低，建议多加练习相关题型。",
        "在解答应用题时，要注意审题和列式过程，这是失分的主要原因。",
        "建议针对错题进行专项训练，特别是几何证明类的题目。",
        "整体来看，你的基础知识掌握得不错，可以尝试更有挑战性的题目。"
      ]
    }

    // 修改 loadAnalysisData 函数，使用测试数据
    const loadAnalysisData = async () => {
      try {
        loading.value = true
        // 模拟 API 调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 使用测试数据
        paperInfo.value = mockData.paper
        questions.value = mockData.questions
        knowledgePoints.value = mockData.knowledgePoints
        aiAnalysis.value = mockData.aiAnalysis

      } catch (error) {
        console.error('加载分析数据出错：', error)
        ElMessage.error('加载分析数据失败，请刷新页面重试')
      } finally {
        loading.value = false
      }
    }

    // 添加查看题目详情的方法（可以先用 ElMessage 提示）
    const showQuestionDetail = (question) => {
      ElMessage({
        message: `这是第 ${questions.value.indexOf(question) + 1} 题，答题${question.isCorrect ? '正确' : '错误'}`,
        type: question.isCorrect ? 'success' : 'warning'
      })
    }

    // 在 setup 函数中添加
    const selectedQuestion = ref(null)

    const handleQuestionClick = (question) => {
      // 如果点击已选中的题目，则取消选中
      if (selectedQuestion.value?.id === question.id) {
        selectedQuestion.value = null
      } else {
        selectedQuestion.value = question
      }
    }

    onMounted(() => {
      loadAnalysisData()
    })

    return {
      paperInfo,
      questions,
      knowledgePoints,
      aiAnalysis,
      radarChartData,
      loading,
      getQuestionTypeName,
      getOptionClass,
      getOptionIconClass,
      getProgressColor,
      getScoreColor,
      getMasteryLevel,
      formatDate,
      exportReport,
      showQuestionDetail,
      selectedQuestion,
      handleQuestionClick
    }
  }
}
</script>

<style scoped>
/* 题干中的图片样式 */
:deep(img) {
  display: inline-block;
  vertical-align: middle;
  margin: 0 4px;
  max-width: 100%;
}

/* 平滑过渡效果 */
.el-tag,
.el-button,
.rounded-lg {
  transition: all 0.3s ease;
}

/* 卡片悬停效果 */
.bg-white.rounded-xl {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.bg-white.rounded-xl:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}
</style>